c++

您所在的位置:网站首页 linked lists c++

c++

2023-04-13 15:53| 来源: 网络整理| 查看: 265

7-2 Merging Linked Lists (25分)

Given two singly linked lists L​1​​=$a​_1$​​→$a​_2$→⋯→$a​_{n-1}$​​→$a​_n$​​ and L​2​​=$b​_1​​$→$b​_2$​​→⋯→$b​_{m-1}$​​→$b​_m​​$​​. If n≥2m, you are supposed to reverse and merge the shorter one into the longer one to obtain a list like a​1​​→a​2​​→b​m​​→a​3​​→a​4​​→b​m−1​​⋯. For example, given one list being 6→7 and the other one 1→2→3→4→5, you must output 1→2→7→3→4→6→5.

Input Specification:

Each input file contains one test case. For each case, the first line contains the two addresses of the first nodes of L​1​​ and L​2​​, plus a positive $N (≤10^5)$ which is the total number of nodes given. The address of a node is a 5-digit nonnegative integer, and NULL is represented by -1.

Then N lines follow, each describes a node in the format:

Address Data Next

where Address is the position of the node, Data is a positive integer no more than 10​5​​, and Next is the position of the next node. It is guaranteed that no list is empty, and the longer list is at least twice as long as the shorter one.

Output Specification:

For each case, output in order the resulting linked list. Each node occupies a line, and is printed in the same format as in the input.

Sample Input:00100 01000 7 02233 2 34891 00100 6 00001 34891 3 10086 01000 1 02233 00033 5 -1 10086 4 00033 00001 7 -1Sample Output:01000 1 02233 02233 2 00001 00001 7 34891 34891 3 10086 10086 4 00100 00100 6 00033 00033 5 -1题目限制:

题目大意:

给定两个链表,现在需要将短的链表按照如下的方法插入到长的链表中,首先将短链表逆序,然后每隔两个节点插入到长的链表中去。

算法思路:

我们使用list1和list2分别保存两个链表,这里假设list1保存的是短的,另外一种情况一样,使用result保存所有插入完毕的链表,其实可以分2种情形考虑这个问题,第一种就是list1还有节点需要插入,那么就把插入2个list2节点和1个list1节点看成一个原子操作,第二种情况就是list1没有节点插入了,那么就依次插入list2节点,直到完毕即可。具体做法如下:

1、使用index_list1 = list1.size()-1,index_list2 = 0,分别表示目前list1和list2的待插入位置2、只要index_list2=0,说明list1还有节点,插入2个list2节点和1个list1节点,转24、如果index_list1


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3